﻿using System;
using System.Text.RegularExpressions;
using System.Web;

namespace Xenta.Utils
{
    /// <summary>
    /// Represents the HTML helper.
    /// </summary>
    public static class HtmlUtility
    {
        #region Constants

        private static readonly Regex TagPattern = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled | RegexOptions.IgnoreCase);

        #endregion

        #region Methods

        /// <summary>
        /// Encodes the string to HTML-encoded string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The encoded string.</returns>
        public static string Encode(string s)
        {
            return HttpUtility.HtmlEncode(s);
        }

        /// <summary>
        /// Decodes the HTML-encoded string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The decoded string.</returns>
        public static string Decode(string s)
        {
            return HttpUtility.HtmlDecode(s);
        }

        /// <summary>
        /// Removes all HTML tags from the input string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The string w/o HTML tags.</returns>
        public static string StripTags(string s)
        {
            return String.IsNullOrEmpty(s) ? s : TagPattern.Replace(s, String.Empty);
        }

        /// <summary>
        /// Converts the plain text string to HTML string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The converted string.</returns>
        public static string FromPlainText(string s)
        {
            if(String.IsNullOrEmpty(s))
            {
                return String.Empty;
            }

            s = StripTags(s);
            s = s.Replace("\r\n", "<br/>");
            s = s.Replace("\r", "<br/>");
            s = s.Replace("\n", "<br/>");
            s = s.Replace("\t", "&nbsp;&nbsp;");

            return s;
        }

        /// <summary>
        /// Converts the HTML string to plain text string.
        /// </summary>
        /// <param name="s">The input string.</param>
        /// <returns>The converted string.</returns>
        public static string ToPlainText(string s)
        {
            if(String.IsNullOrEmpty(s))
            {
                return String.Empty;
            }

            s = s.Replace("<br>", "\n");
            s = s.Replace("<br>", "\n");
            s = s.Replace("<br/>", "\n");
            s = s.Replace("&nbsp;&nbsp;", "\t");
            s = s.Replace("&nbsp;", " ");
            s = StripTags(s);

            return s;
        }

        #endregion
    }
}
